package com.ruyuan.engine.service;

import com.ruyuan.engine.pojo.ClientLog;
import com.ruyuan.engine.pojo.RuleComplexParam;
import com.ruyuan.engine.utils.ClickHouseUtils;
import org.apache.flink.api.common.state.ListState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 顺序查询在clickhouse如何实现
 * */
public class SequenceRuleServiceClickHouseManagerImpl implements SequenceRuleService {


    protected static final Logger log = LoggerFactory.getLogger(SequenceRuleServiceClickHouseManagerImpl.class);


    private static Connection connection;

    static {
        connection = ClickHouseUtils.getConnection();
    }

    public boolean mathRuleSequenceCount(ClientLog clientLog, RuleComplexParam ruleComplexParam) {
        try {
            //需要匹配的步骤
            int totalSize = ruleComplexParam.getSequenceRuleParams().size();

            //后期是动态SQL
            String sql = ruleComplexParam.getSequenceRuleDynamicSql();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();

            /**
             *
             *   ┌─userNo───┬─match3─┬─match2─┬─match1─┐
             *  │ 2A7eGfG1 │       1 │      1 │      1 │
             * └──────────┴────────┴──────
             * */
            int currentStep = 0;
            if (resultSet.next()) {
                //如果满足规则的话，只有一条数据
                for (int i=2;i<totalSize+2;i++) {
                    currentStep += resultSet.getInt(i);
                }
            }
            ruleComplexParam.setSequenceRuleLastStep(ruleComplexParam.getSequenceRuleLastStep()+currentStep);
            return currentStep == totalSize;
        }catch (Exception e) {
            e.printStackTrace();
            log.error("clickhouse连接异常");
        }
        return false;
    }

    @Override
    public boolean mathRuleSequenceCount(ListState<ClientLog> clientLogListState, RuleComplexParam ruleComplexParam) {
        return false;
    }

    @Override
    public boolean mathRuleSequenceCount(RuleComplexParam ruleComplexParam) {
        return false;
    }
}
